package com.wooshow.base.all;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wooshow.base.local.LocalBasicDataSource;
import com.wooshow.base.local.LocalJdbcDaoSupport;

public class MySqlTools extends LocalJdbcDaoSupport {

	private static Log log = LogFactory.getLog(MySqlTools.class);
	
	private String fullpath;
	
	public void backup() {
		String mysql = getBackupCmd();    
		try {
	        java.lang.Runtime.getRuntime().exec("cmd /c " + mysql);
	        log.info("backup successful...");
        } catch (IOException e) {
        	log.error("fail to backup database...");
        } 
	}
	
	private String getBackupCmd() {
		LocalBasicDataSource datasource = (LocalBasicDataSource)getDataSource();
		String url = datasource.getUrl();
		int start = url.lastIndexOf("/") + 1;
		int end = url.indexOf(" ", start);
		if (end <= 0) {
			end = url.length();
		}
		StringBuffer sb = new StringBuffer("mysqldump --routines");
		sb.append(" -u");
		sb.append(datasource.getUsername());
		sb.append(" -p");
		sb.append(datasource.getPassword());
		sb.append(" ");
		sb.append(url.subSequence(start, end));
		sb.append(" > ");
		sb.append(getFullpath());
		return sb.toString();
	}
	
	public String getFullpath() {
		if (StringUtils.isEmpty(fullpath)) {
			fullpath = "./backup.sql";
		}
    	return fullpath;
    }


	public void setFullpath(String fullpath) {
    	this.fullpath = fullpath;
    }
	
	public static void main(String[] args) {
		MySqlTools mysqlTools = (MySqlTools) ApplicationContextHelper.getApplicationContext().getBean("mysqlTools");
		mysqlTools.backup();
	}
}
